package net.chromedpork.scraper.configuration;



import javax.xml.namespace.QName;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import net.chromedpork.hypertext.validation.Assertion;



/**
 *
 *  Abstract XML configuration parser.
 *
 *  @author Inode <inode@chromedpork.net>
 * 
 */

abstract class AbstractConfigurationParser
{
    /**
     *
     *  Parses an XML document into a Document object.
     *
     *  @param config       XML document
     *
     *  @return document
     *
     *  @throws ConfigurationException
     *
     */

    protected static Document parseDocument(String config)
              throws ConfigurationException
    {
        Assertion.notNull(config, "configuration file is null");

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);

        try
        {
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            return (builder.parse(config));
        }

        catch (Exception exception)
        {
            throw new ConfigurationException(exception.getMessage());
        }
    }


    /**
     *
     *  Evaluates an XPath expression on an XML document.
     *
     *  @param document     XML document
     *  @param expression   XPath expression
     *  @param type         XPath return type
     *
     *  @return object enumerated by the expression
     *
     *  @throws ConfigurationException
     *
     */

    protected static Object evaluateXPath(Document document,
                                          String expression,
                                          QName type)
              throws ConfigurationException
    {
        Assertion.notNull(document, "configuration document is null");
        Assertion.notNull(expression, "XPath expression is null");
        Assertion.notNull(type, "XPath return type is null");

        try
        {
            XPath xpath = XPathFactory.newInstance().newXPath();
            XPathExpression expr = xpath.compile(expression);

            return (expr.evaluate(document, type));
        }

        catch (Exception exception)
        {
            throw new ConfigurationException(exception.getMessage());
        }
    }
}
